<template>
  <div class="register-box">
    <div p-5>
      <div class="register-box-top">
        <div class="register-box-top-tittle">{{ boxTittle }}</div>
      </div>
      <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :labelWrap="true">
        <div class="register-box-info">
          <div class="registerBox-tittle">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">案件信息</div>
          </div>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="案件来源" name="sourceId" :labelCol="{ style: { width: '82px' } }">
                <a-select v-model:value="formState.sourceId" placeholder="请选择案件来源" :options="sourceTypeOptions"
                  allowClear>
                </a-select> </a-form-item></a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="其他来源" name="otherSource" :labelCol="{ style: { width: '82px' } }" v-if="sourceTypeOptions?.filter((item) => item.value == formState.sourceId)[0]?.label ==
          '其他'
          ">
                <a-input v-model:value="formState.otherSource" placeholder="请填写其他来源" autocomplete="off"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="16">
              <a-form-item label="案由" name="caseActionId" :labelCol="{ style: { width: '82px' } }">
                <a-button type="primary" @click="showModal" ghost>案由选择</a-button>
                <div class="caseAction">
                  <a-space :size="[8, 16]" wrap style="padding-bottom: 16px">
                    <div v-for="(item, index) in selectedRowNames" class="caseAction-box">
                      <div>{{ item.name }}</div>
                      <div @click="closeCaseAction(item, index)">
                        <CloseCircleFilled style="color: #cccccc; margin-left: 10px; cursor: pointer" />
                      </div>
                    </div>
                  </a-space>
                  <div v-if="selectedRowNames.length == 0" style="color: #999999">请选择案由</div>
                </div>
              </a-form-item>

              <a-modal v-model:open="open" title="案由选择" :width="1000" @ok="handleOk" :destroyOnClose="true">
                <DynamicTable :row-key="(record) => record.id" :row-selection="{
          selectedRowKeys: selectedRowKey,
          onChange: onRowChange,
          preserveSelectedRowKeys: true,
        }" :columns="columns" :data-request="loadData" size="small" bordered :showIndex="true" :showToolBar="false"
                  :autoHeight="true" />
              </a-modal>
            </a-col>
          </a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="关联任务" name="taskNo" :labelCol="{ style: { width: '82px' } }" v-if="sourceTypeOptions?.filter((item) => item.value == formState.sourceId)[0]?.label ==
          '消防监督管理工作中发现'
          ">
                <a-input-group compact>
                  <a-input :value="formState.taskNo" style="width: calc(100% - 88px)" placeholder="请选择任务" />
                  <a-button type="primary" @click="showModal2" ghost>任务选择</a-button>
                </a-input-group>
              </a-form-item>
              <a-modal v-model:open="open2" title="任务选择" :width="1000" @ok="handleOk2">
                <DynamicTable :row-key="(record) => record.id" :row-selection="{
          selectedRowKeys: selectedRowKeys2,
          onChange: onRowChange2,
          type: 'radio',
        }" :columns="columns2" :data-request="loadData2" size="small" bordered :showIndex="true" :showToolBar="false"
                  :autoHeight="true" />
              </a-modal>
            </a-col>
          </a-row>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="16">
              <a-form-item label="简要案情" name="caseBrief" :labelCol="{ style: { width: '82px' } }">
                <a-textarea v-model:value="formState.caseBrief" placeholder="请输入简要案情" :maxlength="128" :rows="4"
                  show-count></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="base-info">
          <div class="registerBox-tittle casePadding">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">基本信息</div>
          </div>
          <a-row :gutter="32">
            <a-col class="gutter-row" :span="12">
              <a-form-item label="当事人类型" name="partyType" class="partyType" :labelCol="{ style: { width: '95px' } }">
                <a-radio-group v-model:value="formState.partyType" option-type="button" button-style="solid"
                  @change="changeParty">
                  <a-radio :value="0">自然人</a-radio>
                  <a-radio :value="1">法人</a-radio>
                  <a-radio :value="2">个体工商户</a-radio>
                  <a-radio :value="3">非法人组织</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="baseBox">
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 0">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="姓名" name="placeName">
                  <a-input v-model:value="formState.placeName" placeholder="请输入姓名" autocomplete="off" show-count
                    :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="性别" name="sex">
                  <a-select v-model:value="formState.sex" placeholder="请选择性别" :options="sexOptions" allowClear>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="出生日期" name="birthDate">
                  <a-date-picker style="width: 100%" v-model:value="formState.birthDate" placeholder="请选择出生日期"
                    :valueFormat="'YYYY-MM-DD'" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="联系电话" name="contactsTel">
                  <a-input v-model:value="formState.contactsTel" placeholder="请输入联系电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="证件类型" name="idType">
                  <a-select v-model:value="formState.idType" placeholder="请选择证件类型" :options="idTypeOptions" allowClear>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="证件号码" name="idCode">
                  <a-input v-model:value="formState.idCode" placeholder="请输入证件号码" autocomplete="off" show-count
                    :maxlength="caseIdcode(formState.idType)" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="住址" name="operateArea">
                  <a-cascader v-model:value="formState.operateArea" :options="addressOptions" placeholder="请选择住址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input v-model:value="formState.operateAddress" placeholder="请输入详细地址" autocomplete="off" show-count
                    :maxlength="68" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 1">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位名称" name="placeName">
                  <a-auto-complete v-model:value="formState.placeName" placeholder="请输入单位名称" :options="placeOptions"
                    @select="onSelect" @search="onSearch" show-count :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input v-model:value="formState.contactsTel" placeholder="请输入单位联系电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader v-model:value="formState.registerArea" :options="addressOptions" placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input v-model:value="formState.registerAddress" placeholder="请输入详细注册地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader v-model:value="formState.operateArea" :options="addressOptions" placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input v-model:value="formState.operateAddress" placeholder="请输入详细经营地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="法人" name="headName">
                  <a-input v-model:value="formState.headName" placeholder="请输入法人姓名" autocomplete="off" show-count
                    :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="法人电话" name="headTel">
                  <a-input v-model:value="formState.headTel" placeholder="请输入法人电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input v-model:value="formState.idCode" placeholder="请输入社会统一信用代码" autocomplete="off" show-count
                    :maxlength="18" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 2">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="字号名称" name="placeName">
                  <a-input v-model:value="formState.placeName" placeholder="请输入字号名称" autocomplete="off" show-count
                    :maxlength="15" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营者姓名" name="headName">
                  <a-input v-model:value="formState.headName" placeholder="请输入经营者姓名" autocomplete="off" show-count
                    :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader v-model:value="formState.registerArea" :options="addressOptions" placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input v-model:value="formState.registerAddress" placeholder="请输入详细注册地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader v-model:value="formState.operateArea" :options="addressOptions" placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input v-model:value="formState.operateAddress" placeholder="请输入详细经营地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input v-model:value="formState.contactsTel" placeholder="请输入单位联系电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input v-model:value="formState.idCode" placeholder="请输入社会统一信用代码" autocomplete="off" show-count
                    :maxlength="18" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="baseBox-body" :gutter="24" v-if="formState.partyType === 3">
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位名称" name="placeName">
                  <a-auto-complete v-model:value="formState.placeName" placeholder="请输入单位名称" :options="placeOptions"
                    @select="onSelect" @search="onSearch" show-count :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="单位联系电话" name="contactsTel">
                  <a-input v-model:value="formState.contactsTel" placeholder="请输入单位联系电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="注册地址" name="registerArea">
                  <a-cascader v-model:value="formState.registerArea" :options="addressOptions" placeholder="请选择注册地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="registerAddress">
                  <a-input v-model:value="formState.registerAddress" placeholder="请输入详细注册地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="经营地址" name="operateArea">
                  <a-cascader v-model:value="formState.operateArea" :options="addressOptions" placeholder="请选择经营地址"
                    :fieldNames="areaFieldNames" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="详细地址" name="operateAddress">
                  <a-input v-model:value="formState.operateAddress" placeholder="请输入详细经营地址" autocomplete="off"
                    show-count :maxlength="68" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="负责人" name="headName">
                  <a-input v-model:value="formState.headName" placeholder="请输入负责人姓名" autocomplete="off" show-count
                    :maxlength="16" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="负责人电话" name="headTel">
                  <a-input v-model:value="formState.headTel" placeholder="请输入负责人电话" autocomplete="off" show-count
                    :maxlength="13" />
                </a-form-item>
              </a-col>
              <a-col class="gutter-row" :span="12">
                <a-form-item label="社会统一信用代码" name="idCode" class="itemForm">
                  <a-input v-model:value="formState.idCode" placeholder="请输入社会统一信用代码" autocomplete="off" show-count
                    :maxlength="18" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
        <div class="register-info">
          <div class="registerBox-tittle">
            <div class="registerBox-tittle-left"></div>
            <div class="registerBox-tittle-right">办案人员</div>
          </div>
          <a-row :gutter="24">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="主办人" name="userName" :labelCol="{ style: { width: '82px' } }">
                <a-select v-model:value="userName" placeholder="请选择主办人" :open="false">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-form-item label="
            协办人" name="organizerId" :labelCol="{ style: { width: '82px' } }">
                <a-select v-model:value="formState.organizerId" placeholder="请选择协作人" :options="organizerOptions"
                  allowClear></a-select>
              </a-form-item> </a-col></a-row>
        </div>
      </a-form>
    </div>
    <div class="bottomBox"></div>
    <div class="bottomBtns" style="z-index: 3">
      <a-space :size="12">
        <a-button @click="cacel" size="large">取消</a-button>
        <a-button type="primary" @click="onSubmit(1)" size="large">保存</a-button>
        <a-button type="primary" @click="onSubmit(0)" size="large">提交</a-button>
      </a-space>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, toRaw, onMounted } from 'vue';
import {
  isPhoneNumberValid,
  isChinaIDCard,
  getKeys,
  isHKCard,
  isPassPortCard,
} from '@/utils/common';
import type { Rule } from 'ant-design-vue/es/form';
import { message } from 'ant-design-vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import { getDeptList, getInfo, getUserList, organizerList } from '@/api/account';
import {
  caseDetail,
  editCaseInfo,
  getAreaList,
  getCaseActionPageList,
  getCaseOption,
  getCaseTaskList,
  getFromType,
  insertCaseInfo,
} from '@/api/administrativePenalty/case-management';
import { getIdType } from '@/api/supervision/create-task';
import { useTable } from '@/components/core/dynamic-table';
import { taskxfInfo } from '@/api/supervision/task-management';
import { getPlaceInfo, getSiteNameList } from '@/api/site';
import { useTabsViewStore } from '@/store/modules/tabsView';
import { CloseCircleFilled } from '@ant-design/icons-vue';

const tabsViewStore = useTabsViewStore();

const [DynamicTable, dynamicTableInstance] = useTable();

const route = useRoute();

const formRef = ref();
const labelCol = {
  style: { width: '109px' },
};

const formState = reactive({
  sourceId: undefined, //案件来源id
  sourceName: '', //案件来源名称
  otherSource: '', //其他来源，来源类型选择“其他”时有值
  caseActionId: '', //案由id
  caseActionName: '', //案由名称
  caseBrief: '', //简要案情
  taskId: '', //任务id，从任务处立案时有值
  taskNo: '', //任务编号
  draftFlag: undefined, //是否为草稿；0.否；1.是
  organizerId: undefined, //协作人
  organizerName: '',
  partyType: 0, //当事人类型
  placeName: '', //单位(场所)名称/姓名/字号名称
  placeId: '',
  sex: undefined, //性别
  birthDate: '', //出生日期
  contactsTel: '', //自然人/单位联系电话
  idType: undefined, //证件类型
  idCode: '', //证件号码
  operateArea: [], //住址
  operateAddress: '', //详细地址
  registerArea: [], //注册地址
  registerAddress: '', //详细注册地址
  headName: '', //法人
  headTel: '', //法人电话
});

const taskIds = ref('');

const boxTittle = ref('立案');

const open = ref<boolean>(false);
const open2 = ref<boolean>(false);

const draftFlag = ref(1);

const selectedRowKey = ref([] as any);
const selectedRowName = ref([] as any);
const selectedRowNames = ref([] as any);

const selectedRowKeys2 = ref([] as any);
const selectedRowName2 = ref('');
const selectedRowList = ref([] as any);

const onRowChange = (selectIds, selectedItems) => {
  selectedRowKey.value = selectIds;
  // selectedRowName.value = selectedItems;
  if (selectIds.length > selectedRowNames.value.length) {
    selectedRowName.value = [];
    selectIds.map((item) => {
      let all = selectedItems.find((items) => {
        if (items && items?.id == item) {
          return items;
        }
      });
      if (all) {
        selectedRowName.value.push(all);
      }
    });

    let ace = selectedRowName.value.concat(selectedRowNames.value);
    let maps = new Map();
    for (let item of ace) {
      if (!maps.has(item.id)) {
        maps.set(item.id, item);
      }
    }
    selectedRowName.value = [...maps.values()];
  } else {
    selectedRowName.value = [];
    selectIds.map((item) => {
      let name = caseDatas.value.find((items) => items.id == item);
      selectedRowName.value.push(name);
    });
  }
};

const onRowChange2 = (selectIds, selectedItems) => {
  selectedRowKeys2.value = selectIds;
  selectedRowName2.value = selectedItems[0].taskNo;
};

const showModal = () => {
  open.value = true;
  if (selectedRowNames.value.length) {
    selectedRowKey.value = [];
    selectedRowNames.value.map((item) => {
      selectedRowKey.value.push(item.id);
    });
  } else {
    selectedRowKey.value = [];
  }
};

const showModal2 = () => {
  open2.value = true;
  if (formState.taskId) {
    selectedRowKeys2.value.push(formState.taskId);
  } else {
    selectedRowKeys2.value = [];
  }
};

const handleOk = (e: MouseEvent) => {
  selectedRowNames.value = [];
  if (selectedRowName.value.length > 0) {
    open.value = false;
    formRef.value.clearValidate('caseActionId');
    selectedRowNames.value = selectedRowName.value;
  } else {
    message.error('请选择案由！');
  }
};

const handleOk2 = (e: MouseEvent) => {
  if (selectedRowKeys2.value != '') {
    open2.value = false;
    formRef.value.clearValidate('taskNo');
    formState.taskId = selectedRowKeys2.value[0];
    formState.taskNo = selectedRowName2.value;
    changePlaceInfo(formState.taskId, 2);
  } else {
    message.error('请选择案由！');
  }
};

const closeCaseAction = (item, index) => {
  // selectedRowName.value.splice(index, 1);
  // selectedRowKey.value.splice(index, 1);
  // selectedRowNames.value.splice(index, 1);

  let arr1 = selectedRowName.value.indexOf(item.name);
  if (arr1 !== -1) {
    selectedRowName.value.splice(index, 1);
  }
  let arr2 = selectedRowKey.value.indexOf(item.id);
  if (arr2 !== -1) {
    selectedRowKey.value.splice(index, 1);
  }
  let arr3 = selectedRowNames.value.indexOf(item);
  if (arr3 !== -1) {
    selectedRowNames.value.splice(index, 1);
  }
};

const columns = [
  {
    title: '案由',
    dataIndex: 'name',
    hideInSearch: true,
  },
  {
    title: '案由',
    dataIndex: 'keyword',
    hideInTable: true,
    formItemProps: {
      labelWidth: 45,
      componentProps: () => {
        return {
          placeholder: '请输入案由搜索',
          autocomplete: 'off',
          disabledLabelWidth: true,
        };
      },
    },
  },
];

const columns2 = [
  {
    title: '任务编号',
    dataIndex: 'taskNo',
    hideInSearch: true,
  },
  {
    title: '当事人类型',
    dataIndex: 'partyType',
    hideInSearch: true,
    customRender: ({ record }) =>
      record.partyType == 0
        ? '自然人'
        : record.partyType == 1
          ? '法人'
          : record.partyType == 2
            ? '个体工商户'
            : record.partyType == 3
              ? '非法人组织'
              : '',
  },
  {
    title: '单位名称',
    dataIndex: 'placeName',
    hideInSearch: true,
  },
  {
    title: '任务',
    dataIndex: 'keyword',
    hideInTable: true,
    formItemProps: {
      labelWidth: 45,
      componentProps: () => {
        return {
          placeholder: '请输入单位名称搜索',
          autocomplete: 'off',
          disabledLabelWidth: true,
        };
      },
    },
  },
];

const caseDatas = ref([] as any);

const loadData = async (params): Promise<API.TableListResult> => {
  const data = await getCaseActionPageList(params);
  data.records.map((item) => {
    caseDatas.value.push(item);
  });
  let as = caseDatas.value;
  let maps = new Map();
  for (let item of as) {
    if (!maps.has(item.id)) {
      maps.set(item.id, item);
    }
  }
  caseDatas.value = [...maps.values()];

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        list: data,
        ...params,
      });
    }, 500);
  });
};

const loadData2 = async (params): Promise<API.TableListResult> => {
  if (route.query.taskId || route.query.id) {
    taskIds.value = (route.query.taskId as any) || caseData.value.taskId;
  }
  let data1 = {
    ...params,
    taskId: taskIds.value || '',
  };
  let data = await getCaseTaskList(data1);

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        list: data,
        ...params,
      });
    }, 500);
  });
};

// const changeCase = () => {
//   console.log(caseDatas.value);
// };

const validateSourceId = async (_rule: Rule, value: string) => {
  if (value === undefined) {
    let message = '请选择案件来源';
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateCaseActionId = async (_rule: Rule, value: string) => {
  if (selectedRowName.value.length == 0) {
    let message = '请选择案由';
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validatePlaceName = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = ['请输入姓名', '请选择单位名称', '请输入字号名称', '请选择单位名称'][
      formState.partyType
    ];
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateOperateArea = async (_rule: Rule, value: string) => {
  if (value == '') {
    let message = ['请选择住址', '请选择经营地址', '请选择经营地址', '请选择经营地址'][
      formState.partyType
    ];
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateContactsTel = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = [
      '请输入联系电话',
      '请输入单位联系电话',
      '请输入单位联系电话',
      '请输入单位联系电话',
    ][formState.partyType];
    return Promise.reject(message);
  } else {
    if (isPhoneNumberValid(value)) {
      return Promise.resolve();
    } else {
      return Promise.reject('请填写正确的手机号码');
    }
  }
};

const validateContactsTels = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = [
      '请输入联系电话',
      '请输入单位联系电话',
      '请输入单位联系电话',
      '请输入单位联系电话',
    ][formState.partyType];
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateContactsTelss = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = ['', '请输入法人电话', '', '请输入负责人电话'][formState.partyType];
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateIdCode = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = [
      '请输入证件号码',
      '请输入社会统一信用代码',
      '请输入社会统一信用代码',
      '请输入社会统一信用代码',
    ][formState.partyType];
    return Promise.reject(message);
  } else if (formState.idType == '身份证') {
    if (isChinaIDCard(value) || formState.partyType !== 0) {
      return Promise.resolve();
    } else {
      let message = [
        '请输入正确的证件号码',
        '请输入正确的社会统一信用代码',
        '请输入正确的社会统一信用代码',
        '请输入正确的社会统一信用代码',
      ][formState.partyType];
      return Promise.reject(message);
    }
  } else if (formState.idType == '港澳通行证') {
    if (isHKCard(value) || formState.partyType !== 0) {
      return Promise.resolve();
    } else {
      return Promise.reject('港澳居民来往内地通行证号码不合规');
    }
  } else if (formState.idType == '护照') {
    if (isPassPortCard(value) || formState.partyType !== 0) {
      return Promise.resolve();
    } else {
      return Promise.reject('护照号码不合规');
    }
  }
};

const validateHeadName = async (_rule: Rule, value: string) => {
  if (value === '') {
    let message = ['', '请输入法人姓名', '请输入经营者姓名', '请输入负责人姓名'][
      formState.partyType
    ];
    return Promise.reject(message);
  } else {
    return Promise.resolve();
  }
};

const validateUserName = async (_rule: Rule, value: string) => {
  return Promise.resolve();
};

const rules = {
  sourceId: [
    {
      required: true,
      validator: validateSourceId,
      trigger: 'change',
    },
  ],
  otherSource: [
    {
      required: true,
      message: '请填写其他来源',
      trigger: 'change',
    },
  ],
  caseActionId: [
    {
      required: true,
      validator: validateCaseActionId,
      trigger: 'change',
    },
  ],
  taskNo: [
    {
      required: true,
      message: '请选择关联任务',
      trigger: 'change',
    },
  ],
  caseBrief: [
    {
      required: true,
      message: '请输入简要案情',
      trigger: 'change',
    },
  ],
  partyType: [
    {
      required: true,
      message: '请选择当事人类型',
      trigger: 'change',
    },
  ],
  placeName: [
    {
      required: true,
      validator: validatePlaceName,
      // message: ['请输入姓名', '请输入单位名称'][formState.partyType],
      trigger: 'change',
    },
  ],
  sex: [
    {
      required: true,
      message: '请选择性别',
      trigger: 'change',
    },
  ],
  birthDate: [
    {
      required: true,
      message: '请选择出生日期',
      trigger: 'change',
    },
  ],
  contactsTel: [
    {
      required: true,
      validator: validateContactsTels,
      trigger: 'blur',
    },
  ],
  idType: [
    {
      required: true,
      message: '请选择证件类型',
      trigger: 'change',
    },
  ],
  idCode: [
    {
      required: true,
      validator: validateIdCode,
      trigger: 'blur',
    },
  ],
  operateArea: [
    {
      required: true,
      validator: validateOperateArea,
      trigger: 'change',
    },
  ],
  operateAddress: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'change',
    },
  ],
  registerArea: [
    {
      required: true,
      message: '请选择注册地址',
      trigger: 'change',
    },
  ],
  registerAddress: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'change',
    },
  ],
  headName: [
    {
      required: true,
      validator: validateHeadName,
      trigger: 'blur',
    },
  ],
  headTel: [
    {
      required: true,
      validator: validateContactsTelss,
      trigger: 'blur',
    },
  ],
  userName: [
    {
      validator: validateUserName,
      trigger: 'change',
      required: true,
    },
  ],
  organizerId: [
    {
      required: true,
      message: '请选择协办人',
      trigger: 'change',
    },
  ],
} as any;

const cacel = () => {
  router.push({
    path: '/administrative-penalty/administrative-penalty/spot-punishment',
  });
};
const onSubmit = (val) => {
  formRef.value
    .validate()
    .then(async () => {
      let idTypeName = '';
      let operateCountyCode = '';
      let operateCounty = '';
      let operateTownCode = '';
      let operateTown = '';
      let registerCountyCode = '';
      let registerCounty = '';
      let registerTownCode = '';
      let registerTown = '';
      let sourceName = '';
      let nameList = [] as any;
      let idList = [] as any;
      if (formState.operateArea) {
        operateCountyCode = formState.operateArea[0];
        operateCounty = getKeys(addressOptions.value, formState.operateArea[0], 'name') as any;
        operateTownCode = formState.operateArea[1];
        operateTown = getKeys(addressOptions.value, formState.operateArea[1], 'name') as any;
      }
      if (formState.registerArea) {
        registerCountyCode = formState.registerArea[0];
        registerCounty = getKeys(registerAddress.value, formState.registerArea[0], 'name') as any;
        registerTownCode = formState.registerArea[1];
        registerTown = getKeys(registerAddress.value, formState.registerArea[1], 'name') as any;
      }
      if (formState.idType) {
        idTypeName = idTypeOptions.value.find((item) => item.value == formState.idType).label;
      }
      if (formState.sourceId) {
        sourceName = sourceTypeOptions.value.find(
          (item) => item.value == formState.sourceId,
        ).label;
      }
      if (selectedRowNames.value.length != 0) {
        selectedRowNames.value.map((item) => {
          idList.push(item.id);
          nameList.push(item.name);
        });
        formState.caseActionId = idList.join(',');
        formState.caseActionName = nameList.join(',');
      }



      let params = {
        id: route.query.id || '',
        organizerId: formState.organizerId || '',
        organizer:
          organizerOptions?.value.find((item) => item.value == formState.organizerId)?.label ||
          '',
        caseType: 1,
        sourceId: formState.sourceId,
        sourceName,
        otherSource: formState.otherSource || '',
        caseActionId: formState.caseActionId || '',
        caseActionName: formState.caseActionName || '',
        caseBrief: formState.caseBrief || '',
        taskId: formState.taskId || '',
        draftFlag: val,
        // enforceWay: formState.enforceWay || '',
        placeInfo: {
          partyType: formState.partyType,
          placeName: formState.placeName || '',
          sex: formState.sex || '',
          birthDate: formState.birthDate || '',
          contactsTel: formState.contactsTel || '',
          idType: formState.idType || '',
          idTypeName,
          idCode: formState.idCode || '',
          operateCountyCode,
          operateCounty,
          operateTownCode,
          operateTown,
          registerCountyCode,
          registerCounty,
          registerTownCode,
          registerTown,
          headName: formState.headName || '',
          headTel: formState.headTel || '',
          operateAddress: formState.operateAddress || '',
          registerAddress: formState.registerAddress || '',
        },
      };
      if (route.query.caseId) {
        params.taskId = route.query.caseId as any;
      }
      if (route.query.id) {
        const res = await editCaseInfo(params);
        if (res.code == 0) {
          if (val == 0) {
            message.success('编辑立案成功！');
          } else {
            message.success('保存立案成功！');
          }
          tabsViewStore.closeCurrentTabToUrl(
            route,
            '/administrative-penalty/administrative-penalty/spot-punishment',
          );
        }
      } else {
        // return;
        const res = await insertCaseInfo(params);
        if (res.code == 0) {
          if (val == 0) {
            message.success('添加立案成功！');
          } else {
            message.success('保存立案成功！');
          }

          tabsViewStore.closeCurrentTabToUrl(
            route,
            '/administrative-penalty/administrative-penalty/spot-punishment',
          );
        }
      }
    })
    .catch((error) => {
      console.log('error', error);
    });
};

const changeParty = () => {
  formState.placeName = '';
  formState.sex = undefined;
  formState.birthDate = '';
  formState.contactsTel = '';
  formState.idType = undefined;
  formState.idCode = '';
  formState.operateArea = [];
  formState.operateAddress = '';
  formState.registerArea = [];
  formState.registerAddress = '';
  formState.headName = '';
  formState.headTel = '';
};

const caseIdcode = (val) => {
  let idTypeName = '';
  if (idTypeOptions.value) {
    idTypeName = idTypeOptions.value.find((item) => item.value == val)?.label;
  }

  switch (idTypeName) {
    case '身份证':
      return 18;
    case '护照':
      return 9;
    case '港澳通行证':
      return 9;
    default:
      return 18;
  }
};

const placeId = ref('');

interface MockVal {
  label: string;
  value: string;
}
const placeOptions = ref<MockVal[]>([]);

const onSelect = (value: string) => {
  changePlaceInfo(value, 1);
  formRef.value.clearValidate('placeName');
  formRef.value.clearValidate('contactsTel');
  formRef.value.clearValidate('operateAddress');
  formRef.value.clearValidate('registerAddress');
  formRef.value.clearValidate('headName');
  formRef.value.clearValidate('headTel');
  formRef.value.clearValidate('operateArea');
  formRef.value.clearValidate('registerArea');
  formRef.value.clearValidate('idCode');
  formRef.value.clearValidate('tudeValue');
};

const changePlaceInfo = async (value, val) => {
  if (val == 1) {
    formState.placeId = value;
    formState.placeName = placeOptions.value.find((item) => item.value == value)?.label as any;

    if (formState.placeId && formState.placeName) {
      let data = await getPlaceInfo(formState.placeId);
      formState.placeId = data.id;
      formState.placeName = data.placeName;
      formState.sex = data.sex;
      formState.birthDate = data.birthDate;
      formState.contactsTel = data.contactsTel;
      formState.idType = data.idType;
      formState.idCode = data.idCode;
      formState.operateAddress = data.operateAddress;
      formState.registerAddress = data.registerAddress;
      formState.headName = data.headName;
      formState.headTel = data.headTel;
      formState.operateArea = [data.operateCountyCode, data.operateTownCode] as any;
      formState.registerArea = [data.registerCountyCode, data.registerTownCode] as any;
    }
  } else if (val == 2) {
    let data = await taskxfInfo(value);
    formState.partyType = data.placeInfo.partyType;
    formState.placeId = data.placeInfo.id;
    formState.placeName = data.placeInfo.placeName;
    formState.sex = data.placeInfo.sex;
    formState.birthDate = data.placeInfo.birthDate;
    formState.contactsTel = data.placeInfo.contactsTel;
    formState.idType = data.placeInfo.idType;
    formState.idCode = data.placeInfo.idCode;
    formState.operateAddress = data.placeInfo.operateAddress;
    formState.registerAddress = data.placeInfo.registerAddress;
    formState.headName = data.placeInfo.headName;
    formState.headTel = data.placeInfo.headTel;
    formState.operateArea = [
      data.placeInfo.operateCountyCode,
      data.placeInfo.operateTownCode,
    ] as any;
    formState.registerArea = [
      data.placeInfo.registerCountyCode,
      data.placeInfo.registerTownCode,
    ] as any;
  }
};

const onSearch = async (searchText: string) => {
  formState.placeName = searchText;

  const res = await getSiteNameList({ placeName: formState.placeName });
  placeOptions.value = res.map((item) => {
    return {
      label: item.placeName,
      value: item.id,
    };
  });
};

//性别
const sexOptions = [
  {
    label: '男',
    value: 1,
  },
  {
    label: '女',
    value: 2,
  },
];

const userName = ref();

//检查类型相关
const sourceTypeOptions = ref();

//立案意见
const opinionOptions = ref();

//协作人
const organizerOptions = ref();

//证件类型
const idTypeOptions = ref();

const caseData = ref();

//区域相关
const addressOptions = ref();
const registerAddress = ref();
const areaFieldNames = {
  label: 'name',
  value: 'id',
};

const organizers = ref({
  type: 0,
});

const taskData = ref();

onMounted(async () => {
  const userData = await getInfo();
  userName.value = userData.userName;

  const from_type = await getFromType();
  if (from_type.code === 0) {
    sourceTypeOptions.value = from_type.data.map((item) => {
      return {
        label: item.configName,
        value: item.id,
      };
    });
  }
  const res_id = await getIdType();
  if (res_id.code === 0) {
    idTypeOptions.value = res_id.data.map((item) => {
      return {
        label: item.configName,
        value: item.id,
      };
    });
  }
  const res_area = await getAreaList();
  if (res_area.code === 0) {
    addressOptions.value = res_area.data[0].children;
    registerAddress.value = res_area.data[0].children;
  }

  const case_option = await getCaseOption();
  if (case_option.code === 0) {
    opinionOptions.value = case_option.data.map((item) => {
      return {
        label: item.configName,
        value: item.id,
      };
    });
  }

  const organizer = await organizerList(organizers.value);

  if (organizer.code === 0) {
    organizerOptions.value = organizer.data.map((item) => {
      return {
        label: item.userName,
        value: item.id,
      };
    });
  }

  if (route.query.id) {
    boxTittle.value = '编辑';
    caseData.value = await caseDetail(route.query.id, 1);
    if (caseData.value.taskId) {
      let data = await taskxfInfo(caseData.value.taskId);
      formState.taskNo = data.taskNo;
    }

    formState.sourceId = caseData.value.sourceId;
    formState.sourceName = caseData.value.sourceName;
    formState.organizerId = caseData.value.organizerId;
    formState.organizerName = caseData.value.organizer;
    formState.otherSource = caseData.value.otherSource;
    formState.caseActionId = caseData.value.caseActionId;
    formState.caseActionName = caseData.value.caseActionName;
    selectedRowName.value = formState.caseActionName.split(',') as any;
    selectedRowKey.value = formState.caseActionId.split(',') as any;
    selectedRowNames.value = selectedRowName.value.map((item, index) => {
      return {
        name: item,
        id: selectedRowKey.value[index],
      };
    });
    // formState.enforceWay = caseData.value.enforceWay;

    formState.caseBrief = caseData.value.caseBrief;
    formState.taskId = caseData.value.taskId;

    formState.partyType = caseData.value.placeInfo.partyType;
    formState.placeName = caseData.value.placeInfo.placeName;
    formState.sex = caseData.value.placeInfo.sex;
    formState.birthDate = caseData.value.placeInfo.birthDate;
    formState.contactsTel = caseData.value.placeInfo.contactsTel;
    formState.idType = caseData.value.placeInfo.idType;
    formState.idCode = caseData.value.placeInfo.idCode;
    formState.operateAddress = caseData.value.placeInfo.operateAddress;
    formState.registerAddress = caseData.value.placeInfo.registerAddress;
    formState.headName = caseData.value.placeInfo.headName;
    formState.headTel = caseData.value.placeInfo.headTel;
    formState.operateArea = [
      caseData.value.placeInfo.operateCountyCode,
      caseData.value.placeInfo.operateTownCode,
    ] as any;
    formState.registerArea = [
      caseData.value.placeInfo.registerCountyCode,
      caseData.value.placeInfo.registerTownCode,
    ] as any;
  }

  if (route.query.taskId) {
    const data = await taskxfInfo(route.query.taskId as any);
    taskData.value = data;
    changePlaceInfo(route.query.taskId, 2);
    formState.taskId = route.query.taskId as any;
    formState.taskNo = taskData.value.taskNo;
    formState.sourceId = '56cb6529f4ae45fb8814b3d13e540a70' as any;
    formState.sourceName = '消防监督管理工作中发现';
  }

  if (route.query.caseId) {
    const data = await taskxfInfo(route.query.caseId as any);
    taskData.value = data;
    formState.partyType = taskData.value.placeInfo.partyType;
    formState.placeName = taskData.value.placeInfo.placeName;
    formState.sex = taskData.value.placeInfo.sex;
    formState.birthDate = taskData.value.placeInfo.birthDate;
    formState.contactsTel = taskData.value.placeInfo.contactsTel;
    formState.idType = taskData.value.placeInfo.idType;
    formState.idCode = taskData.value.placeInfo.idCode;
    formState.operateAddress = taskData.value.placeInfo.operateAddress;
    formState.registerAddress = taskData.value.placeInfo.registerAddress;
    formState.headName = taskData.value.placeInfo.headName;
    formState.headTel = taskData.value.placeInfo.headTel;
    formState.operateArea = [
      taskData.value.placeInfo.operateCountyCode,
      taskData.value.placeInfo.operateTownCode,
    ] as any;
    formState.registerArea = [
      taskData.value.placeInfo.registerCountyCode,
      taskData.value.placeInfo.registerTownCode,
    ] as any;
  }
});
</script>

<style lang="less" scoped>
.register-box {
  background-color: #fff;

  &-top {
    &-tittle {
      padding: 0 0 16px;
      border-bottom: 1px solid rgb(240 240 240 / 100%);
      color: rgb(68 68 68 / 100%);
      font-size: 18px;
      font-weight: 700;
      line-height: 26px;
    }
  }

  &-info {
    .caseAction {
      display: flex;
      border-radius: 4px;
      border: 1px solid rgba(240, 240, 240, 1);
      padding: 16px;
      margin-top: 8px;

      &-box {
        display: flex;
        border-radius: 18px;
        background: rgba(245, 246, 247, 1);
        padding: 5px 8px 5px 8px;
      }
    }
  }

  .base-info {
    .baseBox {
      width: 68%;
      margin: 0 0 16px 95px;
      border: 1px solid #f0f0f0;

      &-body {
        padding: 16px 16px 0 0;
      }
    }

    .partyType {
      .ant-radio-button-wrapper {
        border-color: #f0f0f0;
        border-bottom: 0;
      }

      .ant-radio-button-wrapper:first-child {
        border-inline-start: 1px solid #f0f0f0;
      }

      .ant-radio-button-wrapper:not(:first-child)::before {
        background-color: #f0f0f0;
      }
    }
  }

  .registerBox {
    &-tittle {
      display: flex;
      align-items: center;
      padding: 13px 0;

      &-left {
        height: 14px;
        margin-right: 7px;
        border: 1px solid #0f53ac;
        border-radius: 4px;
      }

      &-right {
        color: rgb(68 68 68 / 100%);
        font-size: 16px;
        font-weight: 400;
        line-height: 24px;
      }
    }
  }

  .casePadding {
    padding: 0 0 13px 0;
  }

  :global(.ant-form-item.partyType) {
    margin-bottom: 0 !important;
  }

  //lable字数大于5时，红点对齐第一行文字
  :global(.itemForm.ant-form-item .ant-form-item-label > label) {
    align-items: baseline;
    line-height: 15px;
  }

  .bottomBox {
    height: 60px;
  }

  .bottomBtns {
    position: fixed;
    bottom: 0;
    width: calc(100% - 200px);
    padding: 8px 20px;
    border-top: 1px solid rgb(240 240 240 / 100%);
    background: rgb(255 255 255 / 100%);
    text-align: right;
  }
}
</style>
